/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dahg.project.istu.controller.bean.menu;

import com.dahg.project.istu.controller.bean.AbstractSingleEntityBean;
import com.dahg.project.istu.controller.model.Menu;
import com.dahg.project.istu.controller.model.Rol;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.Query;

/**
 *
 * @author dahg
 */
@Stateless
public class MenuService extends AbstractSingleEntityBean<Menu> implements IMenuService {

    @Override
    protected Class<Menu> getClazz() {
        return Menu.class;
    }

    @Override    
    public void addMenu(Rol rol, Menu menu) {
        rol.getMenus().add(menu);
        menu.getRoles().add(rol);
        persist(menu);
    }

    @Override
    public List<Menu> getMenuChilds(Menu parent, Rol rol) {
        List<Menu> childs = new ArrayList();
        //No es SQL nativo es JPQL
        String jpql = "select m from Menu m inner join m.roles r where m.padre=:padre and r=:rol order by m.id";
        Query query = getEntityManager().createQuery(jpql)
                .setParameter("padre", parent)
                .setParameter("rol", rol);
        childs.addAll(query.getResultList());
        return childs;
    }

    @Override
    public List<Menu> getRootMenu(Rol rol) {
        List<Menu> childs = new ArrayList();
        //No es SQL nativo es JPQL
        String jpql = "select m from Menu m inner join m.roles r where r=:rol and m.padre is null order by m.id";
        Query query = getEntityManager().createQuery(jpql)
                .setParameter("rol", rol);
        childs.addAll(query.getResultList());
        return childs;
    }

    @Override
    public List<Menu> getAllMenu() {
        List<Menu> childs = new ArrayList();
        String jpql = "select m From Menu m where m.padre is null order by m.id";
        Query query = getEntityManager().createQuery(jpql);
        childs.addAll(query.getResultList());
        return childs;
    }

    @Override
    public List<Menu> getMenuChilds(Menu parent) {
        List<Menu> childs = new ArrayList();
        //No es SQL nativo es JPQL
        String jpql = "select m from Menu m where m.padre=:padre order by m.id";
        Query query = getEntityManager().createQuery(jpql)
                .setParameter("padre", parent);
        childs.addAll(query.getResultList());
        return childs;
    }

}
